<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>5-axios拦截器用法</title>
    <script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script>
    <script src="https://unpkg.com/axios/dist/axios.min.js"></script>

    <style></style>
  </head>
  <body>
    <div id="app"></div>
    <script>
      // 1： 全局注册interceptors.request.use请求拦截器， 设置mytoken
      axios.interceptors.request.use(
        function (config) {
          // console.log(config);/{url: "http:www.localhost:3000/addData", method: "get", headers: {…}, transformRequest: Array(1),
          console.log(config.url); //http:www.localhost:3000/addData
          config.headers.mytoken = 'Are you ok';
          return config;
        },
        function (err) {
          console.log(err);
        }
      );
      // 2：全局注册interceptors.response.use响应拦截器， 就将res.data处理成data
      axios.interceptors.response.use(
        function (res) {
          console.log(res);
          var data = res.data;
          return data;
        },
        function (err) {
          console.log(err);
        }
      );

      //3： 发起数据请求，触发以上2个拦截器
      axios.get('http:www.localhost:3000/addData').then(function (data) {
        console.log(data);
      });
    </script>
  </body>
</html>
